package nthu.web.model.business.persistence;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nthu.web.model.domain.Hadoop;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;


@SuppressWarnings({ "deprecation", "serial" })
public class UploadDao extends ResourceDao<byte[]>{

	public void doPost (HttpServletRequest request, HttpServletResponse response)
                                                 throws ServletException, IOException {
	
		
		String url = "hdfs://localhost:9000/user/bear";
		//String url = "hdfs://hadoop.nchc.org.tw/user/h1506";
		
		HttpSession session = request.getSession();
		String user = (String) session.getAttribute("username");
		
		Configuration conf = new Configuration();
		FileSystem fs = FileSystem.get(URI.create(url), conf);
		
		DiskFileUpload fu = new DiskFileUpload();
		@SuppressWarnings("rawtypes")
		List fileItems = null;
		try {
			fileItems = fu.parseRequest(request);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		ArrayList<String> fileNames = new ArrayList<String>();
		@SuppressWarnings("rawtypes")
		Iterator i = fileItems.iterator();
		while(i.hasNext()){
			FileItem fi = (FileItem)i.next();
			if(fi.getName()!=null && fi.get() != null){
				try{
					fileNames.add(fi.getName());
					OutputStream out = fs.create(new Path(user+"/"+fi.getName()),true);
					out.write(fi.get());
					out.flush();
					out.close();
				}catch(IOException ex){
					fileNames.add("YSLiu.jpg");
					ex = new IOException("file exist");
				}
			}
		}
		/*
		InputStream in = fs.open(new Path(url+"/"+user+"/"+fileNames.get(0)));
		DataInputStream inData = new DataInputStream(in);
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		IOUtils.copyBytes(inData, buffer, conf);
		setModel(request,buffer.toByteArray());*/
		
		Hadoop hadoop = new Hadoop();
		try{
			setModel(request,hadoop.readByte(user+"/"+fileNames.get(0)).toByteArray());
		}catch(NullPointerException ex){
			ex = new NullPointerException("catch io ex");
			setModel(request,hadoop.readByte(user+"/"+"YSLiu.jpg").toByteArray());
		}
		
		//fs.close();			
	}
}
